package com.itheima.dao;

import com.itheima.domain.Student;
import com.itheima.domain.User;
import com.itheima.utils.JDBCUtils;


import java.sql.*;

public class UserdaoImpl implements Userdao{

    @Override
    public int add(User user) {
//获取连接

        Connection con = JDBCUtils.getConnection();
        //定义sql语句  并执行结果
        String sql = "INSERT INTO user VALUES (?,?,?)";
        //获取执行者对象
        PreparedStatement pstmt = null;
        int i = 0;
        try {
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,user.getUid());
            pstmt.setString(2,user.getUsername());
            pstmt.setString(3,user.getPassword());
            //执行sql语句
            i = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(con, pstmt);
        }
        return i;
    }

    @Override
    public User findusername(String username) {
        Connection con = JDBCUtils.getConnection();
        //定义sql
        String sql = "SELECT * FROM user WHERE username=?";
        //获取执行对象
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        User user = null;

        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1,username);
            //执行sql
             rs = pstmt.executeQuery();
             if (rs.next()){
                 user = new User(rs.getInt("Uid"),rs.getString("username"),rs.getString("password"));
             }
        } catch (SQLException e) {
            e.printStackTrace();
        }return user;
    }

    @Override
    public User findusernamepassword(String username, String password) {
        Connection con = JDBCUtils.getConnection();
        //执行sql语句
        String sql = "Select*from user WHERE username=? AND password=?";
        //获取执行者对象
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;
        Student stu = new Student();
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            rs = pstmt.executeQuery();
            if (rs.next()){
                user = new User(rs.getInt("Uid"), rs.getString("username"), rs.getString("password"));
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            JDBCUtils.close(con, pstmt);
        }
        return user;
    }
    }

